# -*- coding:utf-8 -*-
from flask import Blueprint,jsonify,render_template,request,Flask,session, redirect,url_for,current_app
from etc.db_config import get_coon
import pymysql
from misc.app_utils import upload_to_qiniu,md5_value,login_required,special_upload_to_qiniu
import re
import base64
import datetime
from misc.constants import QINIU
import os
from werkzeug.security import generate_password_hash, check_password_hash
import redis
from flask_session import Session

import logging
from logging.handlers import RotatingFileHandler
# 设置⽇志的记录等级
logging.basicConfig(level=logging.DEBUG) # 调试debug级
# 创建⽇志记录器，指明⽇志保存的路径、每个⽇志⽂件的最⼤⼤⼩、保存的⽇志⽂件个数上限
file_log_handler = RotatingFileHandler("log/log.txt", maxBytes=1024*1024*100, backupCount=10)
# 创建⽇志记录的格式 ⽇志等级 输⼊⽇志信息的⽂件名 ⾏数 ⽇志信息
formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
# 为刚创建的⽇志记录器设置⽇志记录格式
file_log_handler.setFormatter(formatter)
# 为全局的⽇志⼯具对象（flask app使⽤的）添加⽇志记录器
logging.getLogger().addHandler(file_log_handler)


import sys  
reload(sys)  
sys.setdefaultencoding('utf8')

app = Flask(__name__,template_folder='../templates')
# 密钥
app.secret_key = "Y\xf5\xe2\xb3Sm\xba\x10\x07P\x84\xce\xd6$tiW(\x19\xd7|e\xb6a"


# 使用redis存信息，默认访问redis 127.0.0.1：6379
app.config['SESSION_TYPE'] = 'redis'
# 访问redis
app.config['SESSION_REDIS'] = redis.Redis(host='localhost', port=6379,db=2)

app.config['PERMANENT_SESSION_LIFETIME'] = 3600 * 3

Session(app)


@app.route('/index',methods=["POST","GET"])
@login_required
def index():

    return render_template("index.html")

@app.route('/login')
def login():

    return render_template("login.html")

@app.route('/login/verify',methods=["POST",])
def login_verify():

    json_dict = request.json
    username = json_dict.get("username")
    password = json_dict.get("password")
    now_time = datetime.datetime.now()

    conn = get_coon()   
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("select * from admin where name=%s;",(username))
        con = cs1.fetchone()
        if con:
            if check_password_hash(con.get("password"),password):
                cs1.execute("update admin set last_login_time=%s where name=%s",(now_time,username))
                # cs1.close()
                conn.commit()
                # conn.close()
                session['username'] = username
                #return redirect(url_for('index'))
                return jsonify(status=0,msg=u"登录成功")
            else:
                # cs1.close()
                # conn.close()
                return jsonify(status=1,msg=u"用户名或密码错误")
        else :
            # cs1.close()
            # conn.close()
            return jsonify(status=1,msg=u"用户名或密码错误")

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()        
        return jsonify(status=1,msg=u"登录失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()

#计算赛事状态的方法
def get_event_type(apply_start_time,apply_end_time,game_start_time,game_end_time):
    now_time = datetime.datetime.now()
    if now_time < apply_start_time:
        return u"未开赛"
		
    if apply_start_time <= now_time and now_time < apply_end_time:
        return u"报名中"
		
    if game_start_time == "" and game_end_time == "":
        if apply_end_time <= now_time:
            return u"等开赛"
    elif  game_start_time != "" and game_end_time != "":
        if apply_end_time <= now_time and now_time < game_start_time:
            return u"等开赛"
        elif game_start_time <= now_time and now_time < game_end_time:
            return u"比赛中"
        elif now_time > game_end_time:
            return u"已结束"

@app.route('/show/game')
@login_required
def show_game():
    
    name = request.args.get("name")

    conn = get_coon()	
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        if name is None:
            cs1.execute("select * from game where delete_flag=0 order by status asc,id desc;")
        else :
            cs1.execute('select * from game where delete_flag=0 and game_name like "%'+name+'%" order by id desc;')
        content = cs1.fetchall()
        data = []
        for i in content:
            data.append(dict(
                create_time = i.get("create_time"),
                icon = QINIU.bucket_url + i.get("icon"),
                banner = QINIU.bucket_url + i.get("game_banner"),
                game_name = i.get("game_name"),
                game_load_url = i.get("game_load_url"),
                tieba_url = i.get("tieba_url"),
                priority = i.get("status"),
                id = i.get("id"),
            ))
        # cs1.close()
        # conn.close()
        return render_template("show_game.html", data=data)

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()		
        return jsonify(status=1,msg=u"展示失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()

@app.route('/show/reservation_list')
@login_required
def show_reservation_list():
   
    name = request.args.get("name")

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        if name is None:
            cs1.execute("select * from college_appointment left join users on college_appointment.user_id = users.id where users.status=0 order by college_appointment.id desc;")
        else :
            cs1.execute('select * from college_appointment left join users on college_appointment.user_id = users.id where users.status=0 and nickname like "%'+name+'%" order by college_appointment.id desc;')
        content = cs1.fetchall()
        data = []
        for i in content:
            data.append(dict(
                nickname = i.get("nickname"),
                create_time = i.get("create_time"),                               
                phone = i.get("phone"),                               
            ))
        # cs1.close()
        # conn.close()
        return render_template("reservation_list.html", data=data)

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"展示失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()
		
@app.route('/show/event')
@login_required
def show_event():

    name = request.args.get("name")

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        if name is None:
            cs1.execute("select * from hot_event left join (select group_concat(award),event_id from event_award group by event_id) as val on hot_event.id=val.event_id order by hot_status desc,hot_event.id desc;")
        else :
            cs1.execute('select * from hot_event left join (select group_concat(award),event_id from event_award group by event_id) as val on hot_event.id=val.event_id where events_title like "%'+name+'%" order by hot_status desc,hot_event.id desc;')
        content = cs1.fetchall()

        cs1.execute("select * from game;")
        games = cs1.fetchall()
        game_types = []
        for i in games:
            game_types.append(i.get("game_name"))

        data = []
        for i in content:
            award_list = i.get("group_concat(award)").split(",")
            data.append(dict(
                first=award_list[0],
                second=award_list[1],
                third=award_list[2],
                event_id=i.get("id"),
                event_title=i.get("events_title"),
                event_type_id=i.get("event_type_id"),
                event_icon= QINIU.bucket_url +i.get("icon"),
                event_award = i.get("total_bonus"),
                event_award_detail = i.get("award_detail"),
                event_introduce = i.get("introduce"),
                game_id = i.get("game_id"),
                event_rule = i.get("rule"),
                max_teams = i.get("max_teams"),
                has_teams = i.get("has_teams"),
                peoples = i.get("team_num"),
                hot_status = 0 if i.get("hot_status")=="\x00" else 1 ,
                event_apply_stime = i.get("apply_start_time"),
                event_apply_etime = i.get("apply_end_time"),
                event_game_stime = "" if i.get("game_start_time")is None else i.get("game_start_time"),
                event_game_etime = "" if i.get("game_end_time")is None else i.get("game_end_time"),
                event_now_type = get_event_type(i.get("apply_start_time"),i.get("apply_end_time"),"" if i.get("game_start_time")is None else i.get("game_start_time"),"" if i.get("game_end_time")is None else i.get("game_end_time")),
				
            ))
        # cs1.close()
        # conn.close()
        return render_template("show_event.html", data=data,game_types=game_types)

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"展示失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()

@app.route('/show/team')
@login_required
def show_team():

    name = request.args.get("name")

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        if name is None:
            cs1.execute("select * from game_team left join team_all_rank on team_all_rank.team_id =game_team.id order by star_flag desc, game_team.id desc;")
        else:
            cs1.execute('select * from game_team left join team_all_rank on team_all_rank.team_id =game_team.id where team_name like "%'+name+'%" order by star_flag desc, game_team.id desc;')
        content = cs1.fetchall()
        data = []
        for i in content:
            team_title = ""
            if i.get("team_type") == 1:
                team_title = u"贴吧战队"
            elif i.get("team_type") == 2:
                team_title = u"竞技战队"
            data.append(dict(
                team_id = i.get("id"),
                team_title=team_title,
                team_point=i.get("competition_point"),
                team_game_num = i.get("join_game_num"),
                team_name=i.get("team_name"),
                team_icon = QINIU.bucket_url +i.get("team_icon"),
                team_details = i.get("team_details"),
                team_create_time = i.get("create_time"),
                star_flag = 0 if i.get("star_flag")=="\x00" else 1 ,
            ))
        # cs1.close()
        # conn.close()
        return render_template("show_team.html", data=data)

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"展示失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()

@app.route('/show/user')
@login_required
def show_user():

    name = request.args.get("name")

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        if name is None:
            cs1.execute("select * from users left join game_team on users.id = game_team.team_leader_id left join user_team on users.id = user_team.user_id where users.status=0 order by user_team.star_team_leader desc,game_team.team_leader_id desc, users.id desc limit 200;")
        else :
            cs1.execute('select * from users left join game_team on users.id = game_team.team_leader_id left join user_team on users.id = user_team.user_id where users.status=0 and nickname like "%'+name+'%" order by user_team.star_team_leader desc,game_team.team_leader_id desc, users.id desc limit 200;')
        content = cs1.fetchall()
        data = []
        for i in content:
            d = dict(
                user_id = i.get("id"),
                user_img= QINIU.bucket_url +i.get("icon"),
                user_name=i.get("nickname"),
                create_time=i.get("create_time"),
                user_mobile = i.get("phone"),
                user_addr = i.get("addr"),
                team_leader_id = i.get("team_leader_id"),
                star_team_leader = 0 if i.get("star_team_leader")=="\x00" else 1 ,
                status = 0 if i.get("status")=="\x00" else 1 ,
            )

            cs1.execute("select identity_type,nickname from user_auths where user_id =%s" % d.get("user_id"))
            result = cs1.fetchall()
            for i in result:
                if i.get("identity_type")=="tieba":
                    d["tieba"] =i.get("nickname")
                elif i.get("identity_type")=="wx":
                    d["wx"] =i.get("nickname")
                elif i.get("identity_type")=="qq":
                    d["qq"] =i.get("nickname")
                else:
                    d["phone"] =i.get("nickname")                    				

            data.append(d)
        # cs1.close()
        # conn.close()
        return render_template("show_user.html", data=data)

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"展示失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()

@app.route('/game/add',methods=["POST",])
@login_required
def game_add():
    
    json_dict = request.json
    title = json_dict.get("title")
    load_url = json_dict.get("load_url")
    tieba_url = json_dict.get("tieba_url") 
    icon = json_dict.get("icon")
    banner = json_dict.get("banner")
    priority = json_dict.get("priority")

    nowtime = datetime.datetime.now()

    img_url = ""
    b = re.match( r'.*,', icon)
    icon = icon.replace(b.group(),"",1)
    imgData = base64.b64decode(icon)
    img_url = upload_to_qiniu(imgData)

    banner_url = ""
    ban = re.match( r'.*,', banner)
    banner = banner.replace(ban.group(),"",1)
    banData = base64.b64decode(banner)
    banner_url = upload_to_qiniu(banData)

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("insert into game(create_time,icon,game_name,game_load_url,tieba_url,game_banner,status) values(%s,%s,%s,%s,%s,%s,%s)",(nowtime,img_url,title,load_url,tieba_url,banner_url,priority))
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"添加成功")

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"添加失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()

@app.route("/game/modify",methods=["POST",])
@login_required
def game_modify():

    json_dict = request.json
    id = json_dict.get("id")
    icon = json_dict.get("icon")
    banner = json_dict.get("banner")
    title = json_dict.get("title")
    is_change = json_dict.get("is_change")
    is_change2 = json_dict.get("is_change2")
    load_url = json_dict.get("load_url")
    tieba_url = json_dict.get("tieba_url")
    priority = json_dict.get("priority")

    new_img_url = ""
    if is_change == "1":
        b = re.match( r'.*,', icon)
        icon = icon.replace(b.group(),"",1)
        imgData = base64.b64decode(icon)
        new_img_url = upload_to_qiniu(imgData)

    new_banner_url = ""
    if is_change2 == "1":
        b = re.match( r'.*,', banner)
        banner = banner.replace(b.group(),"",1)
        imgData = base64.b64decode(banner)
        new_banner_url = upload_to_qiniu(imgData)
  
    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        if new_img_url != "":
            cs1.execute("update game set icon=%s,game_name=%s,game_load_url=%s,tieba_url=%s,status=%s where id=%s",(new_img_url,title,load_url,tieba_url,priority,id))
        else:
            cs1.execute("update game set game_name=%s,game_load_url=%s,tieba_url=%s,status=%s where id=%s",(title,load_url,tieba_url,priority,id))
        
        if new_banner_url != "":
            cs1.execute("update game set game_banner=%s where id=%s",(new_banner_url,id))
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"保存成功")

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"保存失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()

@app.route('/game/delete',methods=["POST",])
@login_required
def game_delete():

    json_dict = request.json
    id = json_dict.get("id")

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("delete from game where id =%s",id)
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"删除成功")

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"删除失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()

@app.route('/event/add',methods=["POST",])
@login_required
def event_add():
    json_dict = request.json
    title = json_dict.get("title")
    type = json_dict.get("type")
    award_type = json_dict.get("award_type")

    prize = json_dict.get("prize")
    prize_len = len(prize)

    rule = json_dict.get("rule")
    icon = json_dict.get("icon")
    game_id = json_dict.get("game_type")
    apply_stime = json_dict.get("apply_stime")
    apply_etime = json_dict.get("apply_etime")
    game_stime = json_dict.get("game_stime")
    game_etime = json_dict.get("game_etime")

    introduce = json_dict.get("introduce")
    max_teams = json_dict.get("max_teams")
    team_num = json_dict.get("team_num")
    hot_status = b'\x00' if json_dict.get("hot_status")== "0" else b'\x01'
    now_time = datetime.datetime.now()

    apply_stime = datetime.datetime.strptime(apply_stime, "%Y-%m-%d %H:%M:%S")
    apply_etime = datetime.datetime.strptime(apply_etime, "%Y-%m-%d %H:%M:%S")
    if apply_etime <= apply_stime:
        return jsonify(status=1,msg=u"报名结束时间不能小于报名开始时间")

    if (game_stime != "" and game_etime !=""):
        game_stime = datetime.datetime.strptime(game_stime, "%Y-%m-%d %H:%M:%S")
        game_etime = datetime.datetime.strptime(game_etime, "%Y-%m-%d %H:%M:%S")
        if game_stime <= apply_etime:
            return jsonify(status=1,msg=u"赛事开始时间不能小于报名结束时间")
        if game_etime <= game_stime:
            return jsonify(status=1,msg=u"赛事结束时间不能小于赛事开始时间")

    img_url = ""
    b = re.match( r'.*,', icon)
    icon = icon.replace(b.group(),"",1)
    imgData = base64.b64decode(icon)
    img_url = upload_to_qiniu(imgData)

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
	
    try:
        cs1.execute("select * from hot_event where flag=0 and hot_status=1")
        content = cs1.fetchall()
        cnt = len(content)
        if cnt ==3 and hot_status == b'\x01':
            cs1.close()
            conn.close()
            return jsonify(status=1,msg=u"热门赛事已满3个")
		
    except Exception as e:
        current_app.logger.error(e)
        cs1.close()
        conn.close()
        return jsonify(status=1,msg=u"添加失败，请联系管理员")

    # finally:
    #     cs1.close()
    #     conn.close()

    start_num = 1
    total_bonus = 0
    award_name = ""
    if int(award_type) == 1 or int(award_type) == 2:
        while start_num < prize_len +1:  
            if (prize.get(str(start_num))).isdigit():
                total_bonus += int(prize.get(str(start_num)))
            start_num +=1
    else :

        award_name = prize.get("1")

    current_app.logger.error(total_bonus)


    try:
        if (game_stime != "" and game_etime !=""):
            cs1.execute("insert into hot_event(create_time,total_bonus,award_name,max_teams,team_num,game_id,award_type,hot_status,introduce,events_title,event_type_id,rule,icon,apply_start_time,apply_end_time,game_start_time,game_end_time) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",(now_time,total_bonus,award_name,max_teams,team_num,game_id,award_type,hot_status,introduce,title,type,rule,img_url,apply_stime,apply_etime,game_stime,game_etime))
        else:
            cs1.execute("insert into hot_event(create_time,total_bonus,award_name,max_teams,team_num,game_id,award_type,hot_status,introduce,events_title,event_type_id,rule,icon,apply_start_time,apply_end_time) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",(now_time,total_bonus,award_name,max_teams,team_num,game_id,award_type,hot_status,introduce,title,type,rule,img_url,apply_stime,apply_etime))

        last_add_event_id = int(cs1.lastrowid)
        nowtime = datetime.datetime.now()

        start2_num = 1
        while start2_num < prize_len +1:
            cs1.execute("insert into event_award values(0,%s,%s,"+str(start2_num)+",%s)",(nowtime,last_add_event_id,prize.get(str(start2_num))))
            start2_num +=1
        # cs1.close()	
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"添加成功")

    except Exception as e:
        # cs1.close()
        # conn.close()
        current_app.logger.error(e)
        return jsonify(status=1,msg=u"添加失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()

@app.route('/event/modify',methods=["POST",])
@login_required
def event_modify():

    json_dict = request.json
    id = json_dict.get("id")
    title = json_dict.get("title")


    rule = json_dict.get("rule")
    icon = json_dict.get("icon")
    is_change = json_dict.get("is_change")
    apply_stime = json_dict.get("apply_stime")
    apply_etime = json_dict.get("apply_etime")
    game_stime = json_dict.get("game_stime")
    game_etime = json_dict.get("game_etime")

    introduce = json_dict.get("introduce")

    hot_status = b'\x00' if json_dict.get("hot_status")== "0" else b'\x01'


    apply_stime = datetime.datetime.strptime(apply_stime, "%Y-%m-%d %H:%M:%S")
    apply_etime = datetime.datetime.strptime(apply_etime, "%Y-%m-%d %H:%M:%S")
    if apply_etime <= apply_stime:
        return jsonify(status=1,msg=u"报名结束时间不能小于报名开始时间")

    if (game_stime != "" and game_etime !=""):
        game_stime = datetime.datetime.strptime(game_stime, "%Y-%m-%d %H:%M:%S")
        game_etime = datetime.datetime.strptime(game_etime, "%Y-%m-%d %H:%M:%S")
        if game_stime <= apply_etime:
            return jsonify(status=1,msg=u"赛事开始时间不能小于报名结束时间")
        if game_etime <= game_stime:
            return jsonify(status=1,msg=u"赛事结束时间不能小于赛事开始时间")

    new_img_url = ""
    if is_change == "1":
        b = re.match( r'.*,', icon)
        icon = icon.replace(b.group(),"",1)
        imgData = base64.b64decode(icon)
        new_img_url = upload_to_qiniu(imgData)

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
	
    try:
        cs1.execute("select hot_status from hot_event where id=%s",id)
        con = cs1.fetchone()
        if con.get("hot_status") == b"\x01" and  hot_status == b'\x01':
            pass
        else : 
            cs1.execute("select * from hot_event where flag=0 and hot_status=1")
            content = cs1.fetchall()
            cnt =  len(content)
            if cnt ==3 and hot_status == b'\x01':
                cs1.close()
                conn.close()
                return jsonify(status=1,msg=u"热门赛事已满3个")
		
    except Exception as e:
        current_app.logger.error(e)
        cs1.close()
        conn.close()
        return jsonify(status=1,msg=u"保存失败，请联系管理员")
	
    # finally:
    #     cs1.close()
    #     conn.close()

    try:
        if (game_stime != "" and game_etime !=""):
            if new_img_url != "":
                cs1.execute("update  hot_event set hot_status=%s,introduce=%s,events_title=%s ,icon=%s, rule=%s,apply_start_time= %s,apply_end_time=%s,game_start_time=%s,game_end_time=%s  where id =%s",(hot_status,introduce,title,new_img_url,rule,apply_stime,apply_etime,game_stime,game_etime,id))
            else:
                cs1.execute("update  hot_event set hot_status=%s,introduce=%s,events_title=%s , rule=%s,apply_start_time= %s,apply_end_time=%s,game_start_time=%s,game_end_time=%s where id =%s",(hot_status,introduce,title,rule,apply_stime,apply_etime,game_stime,game_etime,id))
        else:
            if new_img_url != "":
                cs1.execute("update  hot_event set hot_status=%s,introduce=%s,events_title=%s ,icon=%s, rule=%s,apply_start_time= %s,apply_end_time=%s  where id =%s",(hot_status,introduce,title,new_img_url,rule,apply_stime,apply_etime,id))
            else:
                cs1.execute("update  hot_event set hot_status=%s,introduce=%s,events_title=%s , rule=%s,apply_start_time= %s,apply_end_time=%s where id =%s",(hot_status,introduce,title,rule,apply_stime,apply_etime,id))
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"保存成功")

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"保存失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()

@app.route('/event/delete',methods=["POST",])
@login_required
def event_delete():

    json_dict = request.json
    id = json_dict.get("id")

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("delete from hot_event where id =%s",id)
        cs1.execute("delete from event_award where event_id=%s",id)
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"删除成功")

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
 
        return jsonify(status=1,msg=u"删除失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()

@app.route('/team/modify',methods=["POST",])
@login_required
def team_modify():

    json_dict = request.json
    id = json_dict.get("id")
    title = json_dict.get("title")
    name = json_dict.get("name")
    detail = json_dict.get("detail")
    star_flag = b'\x00' if json_dict.get("star_flag")== "0" else b'\x01'


    if title == u"贴吧战队":
        title = 1
    elif title == u"竞技战队":
         title = 2

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
	
    try:
        cs1.execute("select star_flag from game_team where id=%s",id)
        con = cs1.fetchone()
        if con.get("star_flag") == b"\x01" and  star_flag == b'\x01':
            pass
        else :
            cs1.execute("select * from game_team where star_flag=1")
            content = cs1.fetchall()
            cnt = len(content)
            if cnt ==8 and star_flag == b'\x01':
                cs1.close()
                conn.close()
                return jsonify(status=1,msg=u"明星战队已满8个")
		
    except Exception as e:
        current_app.logger.error(e)
        cs1.close()
        conn.close()
        return jsonify(status=1,msg=u"保存失败，请联系管理员")

    # finally:
    #     cs1.close()
    #     conn.close()
	
    try:
        cs1.execute("update  game_team set star_flag=%s,team_type=%s ,team_name = %s, team_details=%s where id =%s",(star_flag,title,name,detail,id))
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"保存成功")

    except Exception as e:
        # cs1.close()
        # conn.close()
        current_app.logger.error(e)
        return jsonify(status=1,msg=u"保存失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()

@app.route('/team/delete',methods=["POST",])
@login_required
def team_delete():

    json_dict = request.json
    id = json_dict.get("id")

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("delete from game_team where id =%s",id)
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"删除成功")

    except Exception as e:
        # cs1.close()
        # conn.close()
        current_app.logger.error(e)
        return jsonify(status=1,msg=u"删除失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()

@app.route('/user/modify',methods=["POST",])
@login_required
def user_modify():

    json_dict = request.json
    id = json_dict.get("id")
    star_team_leader = b'\x00' if json_dict.get("star_team_leader")== "0" else b'\x01'
    status = b'\x00' if json_dict.get("status")== "0" else b'\x01'

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
	
    if star_team_leader == b'\x01' :
        try:
            cs1.execute("select star_team_leader from user_team where user_id=%s",id)
            con = cs1.fetchone()
            if con.get("star_team_leader") == b"\x01":
                pass
            else :
                cs1.execute("select * from users inner join user_team on users.id = user_team.user_id where users.status=0 and user_team.star_team_leader=1;")
                content = cs1.fetchall()
                cnt = len(content)
                if cnt ==5:
                    cs1.close()
                    conn.close()
                    return jsonify(status=1,msg=u"明星队长已满5个")
		
        except Exception as e:
            current_app.logger.error(e)
            cs1.close()
            conn.close()
            return jsonify(status=1,msg=u"保存失败1，请联系管理员")

        # finally:
        #     cs1.close()
        #     conn.close()
	

    try:
        cs1.execute("update user_team set star_team_leader=%s where user_id=%s",(star_team_leader,id))
        cs1.execute("update users set status=%s where id=%s",(status,id))
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"保存成功")

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"保存失败2，请联系管理员")
		
    finally:
        cs1.close()
        conn.close()

@app.route('/show/news_list')
@login_required
def show_news_list():	

    name = request.args.get("name")

    conn = get_coon()	
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        if name is None:
            cs1.execute("select * from news left join game on news.game_id = game.id left join hot_event on news.event_id = hot_event.id order by news.id desc;")
        else :
            cs1.execute('select * from news left join game on news.game_id = game.id left join hot_event on news.event_id = hot_event.id where title like "%'+name+'%" order by news.id desc;')
        content = cs1.fetchall()
        data = []
        for i in content:
            data.append(dict(
                title = i.get("title"),
                id = i.get("id"),
                create_time = i.get("create_time"),                               
                update_time = i.get("update_time"),                               
                status = i.get("status"),                               
                hot_status = 0 if i.get("hot_status")=="\x00" else 1 ,                        
                icon = QINIU.bucket_url + i.get("icon"),  
                game_name = i.get("game_name") if i.get("game_name") else 'null',
                event_name = i.get("events_title") if i.get("events_title") else 'null',                            
                         
            ))
        # cs1.close()
        # conn.close()
        return render_template("show_news_list.html",data=data)
    
    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"展示失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()
 
    return render_template("show_news_list.html")
		
@app.route('/show/modify_news')
@login_required
def show_modify_news():

    id = request.args.get("id")

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("select * from news where id=%s;"%id)
        con = cs1.fetchone()

        title = con.get("title")
        icon = QINIU.bucket_url + con.get("icon")
        content = con.get("content")
        game_id = con.get("game_id")
        event_id = con.get("event_id")
        a_id , b_id = 0,0
        if game_id == 0 and event_id !=0:
            a_id , b_id = 2,event_id
        elif event_id == 0 and game_id !=0:
            a_id , b_id = 1,game_id

        # current_app.logger.error('aid is' + str(a_id))
        # current_app.logger.error('bid is' + str(b_id))

        script = """$(".addselect option[value='"""+str(a_id)+"""']").attr("selected","selected");\
                var add_type_id = $(".addselect option:selected").val();
                if(add_type_id != 0){
                $.ajax({
                    url:"/app/load/banner_type_detail?id="+add_type_id,
                    dataType:"json",
                    success:function(res){
                        if(res.status == 0){
                          
                            $(".addselect_datail").empty();

                            $.each(res.data,function(i,item){
                                        $(".addselect_datail").append('<option style="color: #000;" value ="'+item.id+'">'+item.title+'</option>');
                                         $(".addselect_datail option[value='"""+str(b_id)+"""']").attr("selected","selected");
                                    });
            
                        }else {
                            alert(res.msg);
                        }
                    }
                })
            }else{
              $(".addselect_datail").empty();
              $(".addselect_datail").append('<option style="color: #000;" value ="0">默认</option>');
            }"""

                   




        write_value = "{% extends 'base.html' %} \
                       {% block title %}"+title+"{% endblock %} \
                       {% block img %}"+icon+"{% endblock %} \
                       {% block content %}"+content+"{% endblock %} \
                       {% block script %}"+script+"{% endblock %}"

        #remove old_file
        my_file = "/home/zenghaisheng/dianjing/admin/templates/news/"+id+".html"
        if os.path.exists(my_file):
            os.remove(my_file)

        with open("/home/zenghaisheng/dianjing/admin/templates/news/"+id+".html","w+")as f:
            f.write(write_value)
        # cs1.close()
        # conn.close()
        return render_template("news/"+id+".html")
    
    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"查看失败，请联系管理员")   

    finally:
        cs1.close()
        conn.close()
	
@app.route('/news/modify',methods=["POST",])
@login_required
def news_modify():

    json_dict = request.json
    title = json_dict.get("title")
    icon = json_dict.get("image")
    news_html = json_dict.get("news_html")
    id = json_dict.get("id")
    type_detail = json_dict.get("type_detail")
    type_detail_id = json_dict.get("type_detail_id")
    update_time = datetime.datetime.now()
    
    img_url = ""
    if icon != "":
        b = re.match( r'.*,', icon)
        icon = icon.replace(b.group(),"",1)
        imgData = base64.b64decode(icon)
        img_url = upload_to_qiniu(imgData)
   
    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        if int(type_detail) == 1:
            if img_url != "":
                cs1.execute("update news set game_id=%s,event_id=%s,title=%s,update_time=%s,content=%s,icon=%s where id=%s",(type_detail_id,0,title,update_time,news_html,img_url,id))      
            else:
                cs1.execute("update news set game_id=%s,event_id=%s,title=%s,update_time=%s,content=%s where id=%s",(type_detail_id,0,title,update_time,news_html,id))      
        elif int(type_detail) == 2:
            if img_url != "":
                cs1.execute("update news set game_id=%s,event_id=%s,title=%s,update_time=%s,content=%s,icon=%s where id=%s",(0,type_detail_id,title,update_time,news_html,img_url,id))      
            else:
                cs1.execute("update news set game_id=%s,event_id=%s,title=%s,update_time=%s,content=%s where id=%s",(0,type_detail_id,title,update_time,news_html,id))
        else:
            if img_url != "":
                cs1.execute("update news set game_id=%s,event_id=%s,title=%s,update_time=%s,content=%s,icon=%s where id=%s",(0,0,title,update_time,news_html,img_url,id))      
            else:
                cs1.execute("update news set game_id=%s,event_id=%s,title=%s,update_time=%s,content=%s where id=%s",(0,0,title,update_time,news_html,id))
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"修改成功")
    
    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"修改失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()

@app.route('/news/type_modify',methods=["POST",])
@login_required
def news_type_modify():	

    json_dict = request.json
    id = json_dict.get("id")
    status = json_dict.get("status")
    hot_status = b'\x00' if json_dict.get("hot_status")== "0" else b'\x01'
	
    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
	
    try:
        cs1.execute("update news set status=%s,hot_status=%s where id =%s",(status,hot_status,id))
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"保存成功")

    except Exception as e:
        # cs1.close()
        # conn.close()
        current_app.logger.error(e)
        return jsonify(status=1,msg=u"保存失败，请联系管理员")
		
    finally:
        cs1.close()
        conn.close()

@app.route('/news/write',methods=["POST",])
@login_required
def news_write():
	
    json_dict = request.json
    title = json_dict.get("title")
    icon = json_dict.get("image")
    news_html = json_dict.get("news_html")
    type_detail = json_dict.get("type_detail")
    type_detail_id = json_dict.get("type_detail_id")

    now_time = datetime.datetime.now()
    	
    img_url = ""
    b = re.match( r'.*,', icon)
    icon = icon.replace(b.group(),"",1)
    imgData = base64.b64decode(icon)
    img_url = upload_to_qiniu(imgData)
   
    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        if int(type_detail) == 1:  
            cs1.execute("insert into news values(0,%s,%s,%s,%s,0,0,0,%s,0)",(title,news_html,now_time,img_url,int(type_detail_id))) 
        elif int(type_detail) == 2:
            cs1.execute("insert into news values(0,%s,%s,%s,%s,0,0,0,0,%s)",(title,news_html,now_time,img_url,int(type_detail_id))) 
        else:
            cs1.execute("insert into news values(0,%s,%s,%s,%s,0,0,0,0,0)",(title,news_html,now_time,img_url)) 
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"添加成功")
    
    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"添加失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()
    

@app.route('/news/delete',methods=["POST",])
@login_required
def news_delete():

    json_dict = request.json
    id = json_dict.get("id")
    
    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("delete from news where id=%s",(id))
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"删除成功")

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"删除失败，请联系管理员")  

    finally:
        cs1.close()
        conn.close()

@app.route('/show/base')
@login_required
def show_base():

    return render_template("base_questions.html")

@app.route('/show/write_news')
@login_required
def show_write_news():

    return render_template("write_news.html")
	
@app.route('/show/banners')
@login_required
def show_banners():

    conn = get_coon()	
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("select * from carousel order by status desc, priority asc, id desc;")
        content = cs1.fetchall()
        data = []
        for i in content:
            data.append(dict(
                create_time = i.get("create_time"),
                icon = QINIU.bucket_url + i.get("icon"),
                type = i.get("type"),
                status = 0 if i.get("status")=="\x00" else 1 ,
                priority = i.get("priority"),
                priority_name = i.get("priority_name"),
                id = i.get("id"),
            ))
        # cs1.close()
        # conn.close()
        return render_template("show_banners.html",data=data)

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()		
        return jsonify(status=1,msg=u"展示失败，请联系管理员")  

    finally:
        cs1.close()
        conn.close()

@app.route('/banners/add',methods=["POST",])
@login_required
def banners_add():

    json_dict = request.json
    icon = json_dict.get("icon")
    type = json_dict.get("type")
    type_detail = json_dict.get("type_detail")
    priority_name = json_dict.get("type_detail_name")

    nowtime = datetime.datetime.now()

    img_url = ""
    b = re.match( r'.*,', icon)
    icon = icon.replace(b.group(),"",1)
    imgData = base64.b64decode(icon)
    img_url = upload_to_qiniu(imgData)

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("insert into carousel(priority,priority_name,create_time,status,type,carousel_event_id,icon) values(%s,%s,%s,%s,%s,%s,%s)",(9,priority_name,nowtime,b'\x00',type,type_detail,img_url))
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"添加成功")

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"添加失败，请联系管理员")  

    finally:
        cs1.close()
        conn.close()
				
@app.route('/load/banner_type_detail')
@login_required
def load_banner_type_detail():

    id = request.args.get("id")
    
    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    
    data = []  
    try:
        if id == '1':
            cs1.execute("select * from game;")     
            content = cs1.fetchall() 

            for i in content:
                data.append(dict(
                    id = i.get("id"),
                    title = i.get("game_name"),
                ))
        if id == '2':
            cs1.execute("select * from hot_event;")       
            content = cs1.fetchall() 
            for i in content:
                data.append(dict(
                    id = i.get("id"),
                    title = i.get("events_title"),
                ))
        if id == '3':
            cs1.execute("select * from news;")       
            content = cs1.fetchall() 
            for i in content:
                data.append(dict(
                    id = i.get("id"),
                    title = i.get("title"),
                ))
        # cs1.close()
        # conn.close()
        return jsonify(status=0,msg=u"添加成功",data=data)

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"添加失败，请联系管理员")  

    finally:
        cs1.close()
        conn.close()
	
@app.route('/banners/modify',methods=["POST",])
@login_required
def banners_modify():

    json_dict = request.json
    id = json_dict.get("id")
    status = b'\x00' if json_dict.get("status")== "0" else b'\x01'
    priority = json_dict.get("priority")
	
    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("update carousel set status=%s,priority=%s where id=%s",(status,priority,id))
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"保存成功")

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"修改失败，请联系管理员")  

    finally:
        cs1.close()
        conn.close()
		
@app.route('/banners/delete',methods=["POST",])
@login_required
def banners_delete():

    json_dict = request.json
    id = json_dict.get("id")
	
    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("delete from carousel  where id=%s",(id))
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"删除成功")

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"删除失败，请联系管理员")  
	
    finally:
        cs1.close()
        conn.close()


@app.route('/show/write_questions')
@login_required
def show_write_questions():

    return render_template("write_questions.html")		
	
@app.route('/questions/write',methods=["POST",])
@login_required
def questions_write():
	
    json_dict = request.json
    news_html = json_dict.get("news_html")
    priority = json_dict.get("priority")
    now_time = datetime.datetime.now()

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("insert into questions_asked values(0,%s,%s,%s)",(now_time,priority,news_html))      
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"添加成功")
    
    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"添加失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()


@app.route('/questions/add',methods=["POST",])
@login_required
def questions_add():

    json_dict = request.json
    news_html = json_dict.get("news_html")
    priority = json_dict.get("priority")
    nowtime = datetime.datetime.now()

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("insert into questions_asked values(0,%s,%s,%s)",(nowtime,priority,news_html))
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"添加成功")

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"添加失败，请联系管理员")  

    finally:
        cs1.close()
        conn.close()
		
@app.route('/show/questions_list')
@login_required
def show_questions_list():	

    conn = get_coon()	
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("select * from questions_asked order by priority asc;")
        content = cs1.fetchall()
        data = []
        for i in content:
            data.append(dict(
                content = i.get("content"),
                priority = i.get("priority"),
                id = i.get("id"),                                                     
            ))
        # cs1.close()
        # conn.close()
        return render_template("show_questions_list.html",data=data)
    
    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"展示失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()
 
@app.route('/questions/type_modify',methods=["POST",])
@login_required
def questions_type_modify():	

    json_dict = request.json
    id = json_dict.get("id")
    priority = json_dict.get("priority")
	
    conn = get_coon()	
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("update questions_asked set priority=%s where id=%s;",(priority,id))
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"修改成功")
    
    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"修改失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()
		
@app.route('/questions/delete',methods=["POST",])
@login_required
def questions_delete():

    json_dict = request.json
    id = json_dict.get("id")
	
    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("delete from questions_asked  where id=%s",(id))
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"删除成功")

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"删除失败，请联系管理员")  

    finally:
        cs1.close()
        conn.close()
		
@app.route('/show/modify_questions')
@login_required
def show_modify_questions():
   
    id = request.args.get("id")
		
    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("select * from questions_asked where id=%s;"%id)
        con = cs1.fetchone()

        priority = con.get("priority")
        content = con.get("content")
			

        write_value = "{% extends 'base_questions.html' %} \
                       {% block content %}"+content+"{% endblock %} \
                       {% block priority %}"+str(priority)+"{% endblock %} \
                       {% block script %}{% endblock %}"
		
        #remove old_file
        my_file = "/home/zenghaisheng/dianjing/admin/templates/questions/"+id+".html"
        if os.path.exists(my_file):
            os.remove(my_file)

        with open("/home/zenghaisheng/dianjing/admin/templates/questions/"+id+".html","w+")as f:
            f.write(write_value)
        # cs1.close()
        # conn.close()
        return render_template("questions/"+id+".html")
    
    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"查看失败，请联系管理员")  

    finally:
        cs1.close()
        conn.close()
	
@app.route('/questions/modify',methods=["POST",])
@login_required
def questions_modify():	

    json_dict = request.json
    id = json_dict.get("id")
    priority = json_dict.get("priority")
    news_html = json_dict.get("news_html")
	
    conn = get_coon()	
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("update questions_asked set priority=%s,content=%s where id=%s;",(priority,news_html,id))
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"修改成功")
    
    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"修改失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()

@app.route('/show/add_event')
@login_required
def show_add_event():

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:        
        cs1.execute("select * from game;")
        games = cs1.fetchall()
        game_types = []
        for i in games:
            game_types.append(i.get("game_name"))
            
        # cs1.close()
        # conn.close()
        return render_template("event_add.html", game_types=game_types)

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"展示失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()

@app.route('/show/add_game')
@login_required
def show_add_game():

   
    return render_template("game_add.html")

@app.route('/show/add_banners')
@login_required
def show_add_banners():

   
    return render_template("banners_add.html")

@app.route('/show/add_questions')
@login_required
def show_add_questions():

   
    return render_template("questions_add.html")



@app.route('/user_message/send')
@login_required
def user_message_send():

   
    return render_template("user_message_send.html")

@app.route('/user_message/sending',methods=["POST",])
@login_required
def user_message_sending():

    json_dict = request.json
    user_type = int(json_dict.get("type"))
    day = json_dict.get("day")
    content = json_dict.get("content")
    now_time = datetime.datetime.now()

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        user_list = []
        cs1.execute('select user_id from user_auths where identity_type="tieba";')
        ids = cs1.fetchall()
        for i in ids:
            user_list.append(i.get("user_id"))

        if user_type == 1:
            if day == "":
                cs1.execute("select id from users where status=0;")
                ids = cs1.fetchall()
                for i in ids:            
                    cs1.execute("insert into user_message values(0,%s,%s,%s)",(now_time,i.get("id"),content))
            else:
                cs1.execute("select user_id from login_record group by user_id;")
                ids = cs1.fetchall()
                for i in ids:            
                    cs1.execute("select max(create_time) from login_record where user_id=%s",(i.get("user_id")))
                    endtime = cs1.fetchone()
                    if endtime.get("max(create_time)") is not None:
                        login_days = ((now_time - endtime.get("max(create_time)")).total_seconds())/(60*60*24)
                        if login_days < int(day):
                            cs1.execute("insert into user_message values(0,%s,%s,%s)",(now_time,i.get("user_id"),content))     

        elif user_type == 2:           
            if day == "": 
                for i in user_list :
                    cs1.execute("insert into user_message values(0,%s,%s,%s)",(now_time,i,content))        
            else:
                for i in user_list:            
                    cs1.execute("select max(create_time) from login_record where user_id=%s",(i))
                    endtime = cs1.fetchone()
                    if endtime.get("max(create_time)") is not None:
                        login_days = ((now_time - endtime.get("max(create_time)")).total_seconds())/(60*60*24)
                        if login_days < int(day):
                            cs1.execute("insert into user_message values(0,%s,%s,%s)",(now_time,i,content))

        else :
            all_user_list = []
            cs1.execute('select id from users where status=0;')
            ids = cs1.fetchall()
            for i in ids:
                all_user_list.append(i.get("id"))

            for i in user_list:
                all_user_list.remove(i)

            if day == "": 
                for i in all_user_list :
                    cs1.execute("insert into user_message values(0,%s,%s,%s)",(now_time,i,content))        
            else:
                for i in all_user_list:            
                    cs1.execute("select max(create_time) from login_record where user_id=%s",(i))
                    endtime = cs1.fetchone()
                    if endtime.get("max(create_time)") is not None:
                        login_days = ((now_time - endtime.get("max(create_time)")).total_seconds())/(60*60*24)
                       
                        if login_days < int(day):
                            cs1.execute("insert into user_message values(0,%s,%s,%s)",(now_time,i,content))
            
        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"发送成功")

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"发送失败，请联系管理员")

    finally:
        cs1.close()
        conn.close()

@app.route('/get/award_detail',methods=["POST",])
@login_required
def get_award_detail():

    json_dict = request.json
    _id = json_dict.get("id")

    conn = get_coon()
    cs1 = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cs1.execute("select group_concat(award) from event_award where event_id=%s",(_id))
        content = cs1.fetchone()
        
        award = content.get("group_concat(award)")
        award = award.split(",")

        # cs1.close()
        conn.commit()
        # conn.close()
        return jsonify(status=0,msg=u"显示成功",award=award)

    except Exception as e:
        current_app.logger.error(e)
        # cs1.close()
        # conn.close()
        return jsonify(status=1,msg=u"显示失败，请联系管理员")  

    finally:
        cs1.close()
        conn.close()

@app.route('/upload/image',methods=["POST",])
@login_required
def upload_image_to_qiniu():

    from werkzeug.utils import secure_filename

    file = request.files['file']
    basepath = os.path.dirname(__file__)
    upload_path = os.path.join(basepath, 'static/fileimages',secure_filename(file.filename))
    upload_path = upload_path.replace('app/','')
    current_app.logger.error(upload_path)
    file.save(upload_path)

    # _content = self._file_obj.read() if self._file_obj is not None else None
    key = special_upload_to_qiniu(upload_path)

    try:
        if os.path.isfile(upload_path):
            os.remove(upload_path)
    except Exception as e:
        current_app.logger.error(e)

    url = QINIU.bucket_url + key
    return jsonify(link=url)  


import random,hashlib,uuid,time,requests,urllib,hmac,xmltodict
from Crypto.Cipher import AES
 
def _get_32_str():
        _str = ''
        for i in range(32):
            a  = random.choice("1234567890abcdefghijklkmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ")
            _str += a
        return _str

def _get_sign(_str,key):
    m2 = hashlib.md5()

    m2.update((_str+'&key=%s'%key).encode())
    current_app.logger.error((_str+'&key=%s'%key))

    return m2.hexdigest().upper()

def _get_hmac_sha256(_str,key):
    
    _str = _str+'&key=%s'%key
    signature = hmac.new(key, _str, digestmod=hashlib.sha256).hexdigest().upper()

    return signature

class AESCipher():
    """
    Usage:
        c = AESCipher('password').encrypt('message')
        m = AESCipher('password').decrypt(c)
    Tested under Python 3 and PyCrypto 2.6.1.
    """
    def __init__(self, key):
        self.key = hashlib.md5(key.encode('utf8')).hexdigest()

        # Padding for the input string --not
        # related to encryption itself.
        self.BLOCK_SIZE = 32  # Bytes
        self.pad = lambda s: s + (self.BLOCK_SIZE - len(s) % self.BLOCK_SIZE) * \
                        chr(self.BLOCK_SIZE - len(s) % self.BLOCK_SIZE)
        self.unpad = lambda s: s[:-ord(s[len(s) - 1:])]


    def encrypt(self, raw):
        raw = self.pad(raw)
        cipher = AES.new(self.key, AES.MODE_ECB)
        return base64.b64encode(cipher.encrypt(raw))

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        cipher = AES.new(self.key, AES.MODE_ECB)
        return self.unpad(cipher.decrypt(enc)).decode('utf8')



@app.route('/wechat/pay',methods=["POST",])
@login_required
def wechat_test():

    """
    此处为统一订单，需替换的变量有用户ip地址，附加自定义数据，商品简单描述、用户的openid
    """

    json_dict = request.json
    #用户ip地址
    ip = json_dict.get("ip")
    #是否在微信客户端打开，手机支付模式
    is_wechat_open = json_dict.get("is_wechat_open")
    #是否在电脑端打开，扫码支付模式
    is_pc_open = json_dict.get("check_is_pc")
    current_app.logger.error(is_pc_open)

    #用户的openid
    openid = 'o0-cG1FbZ6pFi4rFHjMFmbYMCS2M'

    #统一下单
    base_url = "https://api.mch.weixin.qq.com/pay/unifiedorder"
    #key
    key = 'pSGKRL1HUxtsDTFinr9gGbKGEXSejONr'

    #微信分配的公众账号ID
    appid = "wx2535ac9f0488e2bf"
    #微信支付分配的商户号
    mch_id = "1504269991"
    #附加自定义数据String(127)
    attach = "white here what you want"
    #随机字符串
    nonce_str = _get_32_str()
    #商品简单描述String(128)
    if not is_wechat_open :
        body = "易战平台-彩豆充值"
    else :
        body = "易战-游戏"
    #商户订单号
    out_trade_no = str(uuid.uuid4()).replace("-",'')
    #商品ID String(32)
    product_id = '1223541321408587698758'
    #金额，单位是分
    total_fee = 1
    #用户ip地址
    spbill_create_ip = ip

    now_time = int(time.time())
    #交易起始时间
    time_start = time.strftime("%Y%m%d%H%M%S",time.localtime(now_time))
    #交易结束时间 1200是时间戳的20分钟，即有效期20分钟
    time_expire = time.strftime("%Y%m%d%H%M%S",time.localtime(now_time+1200))
    #接收微信支付异步通知回调地址
    notify_url = 'http://zhs.dev-juyouxiao.com:10088/app/index_get_wechat_pay_notice'
    #交易类型
    if not is_wechat_open:
        trade_type = 'MWEB'
        if is_pc_open == "PC":
           trade_type = 'NATIVE'
    else :
        trade_type = 'JSAPI'


    #场景信息
    if not is_wechat_open:
        scene_info = {"h5_info":{"type":"Wap","wap_url":"http://zhs.dev-juyouxiao.com:10088/app/index","wap_name":"易战充值"}}
        if is_pc_open == "PC":
           scene_info = {"store_info" : {"id": "TZKJ001","name": "添昌科技","area_code": "524000","address": "方圆E时光" }}
    else :
        scene_info = {"store_info" : {"id": "TZKJ001","name": "添昌科技","area_code": "524000","address": "方圆E时光" }}

    #签名
    if not is_wechat_open:
        stringA = 'appid={}&attach={}&body={}&mch_id={}&nonce_str={}&notify_url={}&out_trade_no={}&product_id={}&scene_info={}&spbill_create_ip={}&time_expire={}&time_start={}&total_fee={}&trade_type={}'\
            .format(appid,attach,body,mch_id,nonce_str,notify_url,out_trade_no,product_id,scene_info,spbill_create_ip,time_expire,time_start,total_fee,trade_type)

        sign = _get_sign(stringA,key)

        stringB = '<xml><appid>{}</appid><attach>{}</attach><body>{}</body><mch_id>{}</mch_id><nonce_str>{}</nonce_str><notify_url>{}</notify_url><out_trade_no>{}</out_trade_no><product_id>{}</product_id><scene_info>{}</scene_info><spbill_create_ip>{}</spbill_create_ip><time_expire>{}</time_expire><time_start>{}</time_start><total_fee>{}</total_fee><trade_type>{}</trade_type>'\
            .format(appid,attach,body,mch_id,nonce_str,notify_url,out_trade_no,product_id,scene_info,spbill_create_ip,time_expire,time_start,total_fee,trade_type)

        data =  stringB + '<sign>%s</sign>'%sign +'</xml>'
        current_app.logger.error(data)
        ret = requests.post(base_url, data = data)
        current_app.logger.error(ret.text)

        return_json = xmltodict.parse(ret.text)

        if is_pc_open == "PC":
            code_url = return_json.get('xml').get('code_url')
            current_app.logger.error(code_url)
            return jsonify(status=0,msg=code_url)

        mweb_url = return_json.get('xml').get('mweb_url')

        # redirect_url = 'https://juyouxiao.com'
        # new_redirect_url = urllib.urlencode(redirect_url)
        # new_redirect_url = 'https%3a%2f%2fjuyouxiao.com'
        # 支付后回调链接
        new_redirect_url = 'http%3a%2f%2fzhs.dev-juyouxiao.com%3a10088%2fapp%2findex'

        return jsonify(status=0,msg=mweb_url+'&redirect_url=' +new_redirect_url)

    else :
        #正常逻辑下的签名
        stringA = 'appid={}&attach={}&body={}&mch_id={}&nonce_str={}&notify_url={}&openid={}&out_trade_no={}&product_id={}&scene_info={}&spbill_create_ip={}&time_expire={}&time_start={}&total_fee={}&trade_type={}'\
            .format(appid,attach,body,mch_id,nonce_str,notify_url,openid,out_trade_no,product_id,scene_info,spbill_create_ip,time_expire,time_start,total_fee,trade_type)

        sign = _get_sign(stringA,key)

        stringB = '<xml><appid>{}</appid><attach>{}</attach><body>{}</body><mch_id>{}</mch_id><nonce_str>{}</nonce_str><notify_url>{}</notify_url><openid>{}</openid><out_trade_no>{}</out_trade_no><product_id>{}</product_id><scene_info>{}</scene_info><spbill_create_ip>{}</spbill_create_ip><time_expire>{}</time_expire><time_start>{}</time_start><total_fee>{}</total_fee><trade_type>{}</trade_type>'\
            .format(appid,attach,body,mch_id,nonce_str,notify_url,openid,out_trade_no,product_id,scene_info,spbill_create_ip,time_expire,time_start,total_fee,trade_type)

        data =  stringB + '<sign>%s</sign>'%sign +'</xml>'
        current_app.logger.error(data)
        ret = requests.post(base_url, data = data)
        current_app.logger.error(ret.text)

        return_json = xmltodict.parse(ret.text)
        prepay_id = return_json.get('xml').get('prepay_id')
        timeStamp = str(int(time.time()))
        signType = 'MD5'
        #随机字符串
        nonce_str = _get_32_str()

        #调起客户端重新需要新的签名
        new_stringA = 'appId={}&nonceStr={}&package={}&signType={}&timeStamp={}'\
            .format(appid,nonce_str,'prepay_id=%s'%prepay_id,signType,timeStamp)
        current_app.logger.error(new_stringA)
        paySign = _get_sign(new_stringA,key)
        current_app.logger.error(paySign)
        _data = dict(
                appId = appid,
                timeStamp = timeStamp,
                nonceStr = nonce_str,
                package = "prepay_id=%s"%prepay_id,
                signType = signType,
                paySign = paySign,
            )

        return jsonify(status=1,data=_data)


@app.route('/wechat/query_order',methods=["POST",])
@login_required
def query_order():
    
    """
    此处为查询订单，需替换的变量有商户订单号
    """

    #商户订单号
    out_trade_no = "4ad63c15be184d32af73a98b9f67705b"

    #查询订单
    base_url = "https://api.mch.weixin.qq.com/pay/orderquery"
    #微信分配的公众账号ID
    appid = "wx2535ac9f0488e2bf"
    #微信支付分配的商户号
    mch_id = "1504269991"
    #key
    key = 'pSGKRL1HUxtsDTFinr9gGbKGEXSejONr'
    #随机字符串
    nonce_str = _get_32_str()

    #签名
    stringA = 'appid={}&mch_id={}&nonce_str={}&out_trade_no={}'\
        .format(appid,mch_id,nonce_str,out_trade_no)

    sign = _get_sign(stringA,key)

    stringB = '<xml><appid>{}</appid><mch_id>{}</mch_id><nonce_str>{}</nonce_str><out_trade_no>{}</out_trade_no>'\
        .format(appid,mch_id,nonce_str,out_trade_no)

    data =  stringB + '<sign>%s</sign>'%sign +'</xml>'
    current_app.logger.error(data)
    ret = requests.post(base_url, data = data)
    current_app.logger.error(ret.text)

    return jsonify(status=0,msg="查询订单成功")

@app.route('/wechat/close_order',methods=["POST",])
@login_required
def close_order():
    
    """
    此处为关闭订单，需替换的变量有商户订单号
    """

    #商户订单号
    out_trade_no = "a9c793d3ef75465f90e61c7e167ebb91"

    #关闭订单
    base_url = "https://api.mch.weixin.qq.com/pay/closeorder"
    #微信分配的公众账号ID
    appid = "wx2535ac9f0488e2bf"
    #微信支付分配的商户号
    mch_id = "1504269991"
    #key
    key = 'pSGKRL1HUxtsDTFinr9gGbKGEXSejONr'
    #随机字符串
    nonce_str = _get_32_str()

    #签名
    stringA = 'appid={}&mch_id={}&nonce_str={}&out_trade_no={}'\
        .format(appid,mch_id,nonce_str,out_trade_no)

    sign = _get_sign(stringA,key)

    stringB = '<xml><appid>{}</appid><mch_id>{}</mch_id><nonce_str>{}</nonce_str><out_trade_no>{}</out_trade_no>'\
        .format(appid,mch_id,nonce_str,out_trade_no)

    data =  stringB + '<sign>%s</sign>'%sign +'</xml>'
    current_app.logger.error(data)
    ret = requests.post(base_url, data = data)
    current_app.logger.error(ret.text)

    return jsonify(status=0,msg="关闭订单成功")

@app.route('/wechat/refund_order',methods=["POST",])
@login_required
def refund_order():
    
    """
    此处为退款订单，需替换的变量有商户订单号、订单总金额、退款总金额
    退款需要微信商户平台的API证书
    """

    #商户订单号
    out_trade_no = "ef1fc162266c4e1599f8ec5d9d34a47f"
    #订单总金额，单位为分
    total_fee = 1
    #退款总金额，单位为分,不能超过订单总金额
    refund_fee = 1

    #退款订单
    base_url = "https://api.mch.weixin.qq.com/secapi/pay/refund"
    #API证书地址
    cert_path = "/home/zenghaisheng/weixin_key/apiclient_cert.pem"
    key_path = "/home/zenghaisheng/weixin_key/apiclient_key.pem"
    #微信分配的公众账号ID
    appid = "wx2535ac9f0488e2bf"
    #微信支付分配的商户号
    mch_id = "1504269991"
    #商户退款单号
    out_refund_no = str(uuid.uuid4()).replace("-",'')
    #key
    key = 'pSGKRL1HUxtsDTFinr9gGbKGEXSejONr'
    #随机字符串
    nonce_str = _get_32_str()
    #退款结果通知url
    notify_url = "http://zhs.dev-juyouxiao.com:10088/app/index_get_wechat_refund_notice"

    #签名
    stringA = 'appid={}&mch_id={}&nonce_str={}&notify_url={}&out_refund_no={}&out_trade_no={}&refund_fee={}&total_fee={}'\
        .format(appid,mch_id,nonce_str,notify_url,out_refund_no,out_trade_no,refund_fee,total_fee)

    sign = _get_sign(stringA,key)

    stringB = '<xml><appid>{}</appid><mch_id>{}</mch_id><nonce_str>{}</nonce_str><notify_url>{}</notify_url><out_refund_no>{}</out_refund_no><out_trade_no>{}</out_trade_no><refund_fee>{}</refund_fee><total_fee>{}</total_fee>'\
        .format(appid,mch_id,nonce_str,notify_url,out_refund_no,out_trade_no,refund_fee,total_fee)

    data =  stringB + '<sign>%s</sign>'%sign +'</xml>'
    current_app.logger.error(data)
    ret = requests.post(base_url, data = data,cert = (cert_path,key_path))
    current_app.logger.error(ret.text)

    return jsonify(status=0,msg="退款成功")


@app.route('/wechat/refund_query',methods=["POST",])
@login_required
def refund_query():
    
    """
    此处为查询退款订单，需替换的变量有商户退款单号
    """

    #商户退款单号
    out_refund_no = "Y1ua5NhEfVER8TKfYEPsS64pUrLLpXL8"

    #查询退款订单
    base_url = "https://api.mch.weixin.qq.com/pay/refundquery"
    #微信分配的公众账号ID
    appid = "wx2535ac9f0488e2bf"
    #微信支付分配的商户号
    mch_id = "1504269991"
    #key
    key = 'pSGKRL1HUxtsDTFinr9gGbKGEXSejONr'
    #随机字符串
    nonce_str = _get_32_str()


    #签名
    stringA = 'appid={}&mch_id={}&nonce_str={}&out_refund_no={}'\
        .format(appid,mch_id,nonce_str,out_refund_no)

    sign = _get_sign(stringA,key)

    stringB = '<xml><appid>{}</appid><mch_id>{}</mch_id><nonce_str>{}</nonce_str><out_refund_no>{}</out_refund_no>'\
        .format(appid,mch_id,nonce_str,out_refund_no)

    data =  stringB + '<sign>%s</sign>'%sign +'</xml>'
    current_app.logger.error(data)
    ret = requests.post(base_url, data = data)
    current_app.logger.error(ret.text)

    return jsonify(status=0,msg="查询退款成功")

@app.route('/wechat/downloadbill',methods=["POST",])
@login_required
def downloadbill():
    
    """
    此处为下载对账单，需替换的变量有对账单日期、账单类型
    """

    #对账单日期，格式：20140603
    bill_date = "20181010"
    """
    账单类型
    ALL，返回当日所有订单信息，默认值
    SUCCESS:返回当日成功支付的订单
    REFUND:返回当日退款订单
    RECHARGE_REFUND:返回当日充值退款订单
    """
    bill_type = "ALL"


    #下载对账单
    base_url = "https://api.mch.weixin.qq.com/pay/downloadbill"
    #微信分配的公众账号ID
    appid = "wx2535ac9f0488e2bf"
    #微信支付分配的商户号
    mch_id = "1504269991"
    #key
    key = 'pSGKRL1HUxtsDTFinr9gGbKGEXSejONr'
    #随机字符串
    nonce_str = _get_32_str()


    #签名
    stringA = 'appid={}&bill_date={}&bill_type={}&mch_id={}&nonce_str={}'\
        .format(appid,bill_date,bill_type,mch_id,nonce_str)

    sign = _get_sign(stringA,key)

    stringB = '<xml><appid>{}</appid><bill_date>{}</bill_date><bill_type>{}</bill_type><mch_id>{}</mch_id><nonce_str>{}</nonce_str>'\
        .format(appid,bill_date,bill_type,mch_id,nonce_str)

    data =  stringB + '<sign>%s</sign>'%sign +'</xml>'
    current_app.logger.error(data)
    ret = requests.post(base_url, data = data)
    current_app.logger.error(ret.text)

    return jsonify(status=0,msg="下载对账单成功")

@app.route('/wechat/downloadfundflow',methods=["POST",])
@login_required
def downloadfundflow():
    
    """
    此处为下载资金账单，需替换的变量有对账单日期、账单类型、app.secret_key
    需导入证书地址
    """

    #资金账单日期，格式：20140603
    bill_date = "20181011"
    """
    资金账户类型
    账单的资金来源账户：
    Basic  基本账户
    Operation 运营账户
    Fees 手续费账户
    """
    account_type = "Basic"
    #API证书地址
    cert_path = "/home/zenghaisheng/weixin_key/apiclient_cert.pem"
    key_path = "/home/zenghaisheng/weixin_key/apiclient_key.pem"

    #下载资金账单
    base_url = "https://api.mch.weixin.qq.com/pay/downloadfundflow"
    #微信分配的公众账号ID
    appid = "wx2535ac9f0488e2bf"
    #微信支付分配的商户号
    mch_id = "1504269991"
    #key
    key = 'pSGKRL1HUxtsDTFinr9gGbKGEXSejONr'
    #随机字符串
    nonce_str = _get_32_str()

    #签名
    stringA = 'account_type={}&appid={}&bill_date={}&mch_id={}&nonce_str={}'\
        .format(account_type,appid,bill_date,mch_id,nonce_str)

    sign = _get_hmac_sha256(stringA,key)

    stringB = '<xml><account_type>{}</account_type><appid>{}</appid><bill_date>{}</bill_date><mch_id>{}</mch_id><nonce_str>{}</nonce_str>'\
        .format(account_type,appid,bill_date,mch_id,nonce_str)

    data =  stringB + '<sign>%s</sign>'%sign +'</xml>'
    current_app.logger.error(data)
    ret = requests.post(base_url, data = data,cert = (cert_path,key_path))
    current_app.logger.error(ret.text)

    return jsonify(status=0,msg="下载资金账单成功")

@app.route('/index_get_wechat_pay_notice',methods=["POST","GET"])
def index_get_wechat_pay_notice():
    #支付结果通知

    if request.method == 'POST':
        #form = request.form
        current_app.logger.error(request.data)
        return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>"

    return render_template("index.html")

@app.route('/index_get_wechat_refund_notice',methods=["POST","GET"])
def index_get_wechat_refund_notice():
    #退款结果通知

    #key
    key = 'pSGKRL1HUxtsDTFinr9gGbKGEXSejONr'

    if request.method == 'POST':
        #form = request.form
        current_app.logger.error(request.data)

        return_json = xmltodict.parse(request.data)
        req_info = return_json.get('xml').get('req_info')
        current_app.logger.error(req_info)
        #退款结果明文信息
        _information = AESCipher(key).decrypt(req_info)
        current_app.logger.error(_information)

        return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>"

    return render_template("index.html")